package models

import (
	"GoTime/response"
	. "GoTime/utils"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"strings"
	"time"

	"github.com/spf13/cast"
	"xorm.io/builder"
)

type Examiner struct {
	Id               int       `xorm:"not null pk autoincr comment('自增主键') INT(11)"`
	UserId           int       `xorm:"not null comment('用户id外键关联dts_user中的id') index INT(11)"`
	SchoolId         int       `xorm:"not null comment('驾校id外键关联dts_school中的自增id') index INT(11)"`
	IcId             int       `xorm:"default 0 comment('IC卡id,考核员可以没有IC卡也可以拥有多张IC卡，当前为生效IC卡id') INT(11)"`
	FingerId         int       `xorm:"default 0 comment('指纹id，考核员可以拥有多个指纹记录，当前为生效指纹id') INT(11)"`
	PortraitId       int       `xorm:"default 0 comment('头像id，考核员可以拥有多个头像记录，当前为生效头像id') INT(11)"`
	LicenceNumber    string    `form:"licence_number" xorm:"default '' comment('驾驶证号') VARCHAR(128)"`
	LicenceGrantDate time.Time `xorm:"comment('驾驶证初领日期 YYYYMMDD') DATE"`
	OccupationNumber string    `form:"occupation_number" xorm:"not null default '' comment('教练员职业资格证件号') VARCHAR(128)"`
	OccupationRank   string    `form:"occupation_rank" xorm:"default '1' comment('教练员职业资格等级，1：一级，2：二级，3：三级，4：四级') ENUM('1','2','3','4')"`
	DrivingCarType   string    `form:"driving_car_type" xorm:"default 'C1' comment('准驾车型') ENUM('A1','A2','A3','B1','B2','C1','C2','C3','C4','C5','D','E','F','M','N','P')"`
	TeachingCarType  string    `form:"teaching_car_type" xorm:"default 'C1' comment('准教车型') ENUM('A1','A2','A3','B1','B2','C1','C2','C3','C4','C5','D','E','F','M','N','P')"`
	EntryDate        time.Time `xorm:"comment('入职日期 YYYYMMDD') DATE"`
	DepartureDate    time.Time `xorm:"comment('离职日期 YYYYMMDD') DATE"`
	Status           string    `form:"status" xorm:"default '1' comment('0：在职, 1：离职') ENUM('0','1')"`
	ApprovalStatus   string    `xorm:"default '0' comment('考核员提交运管审核状态，0:待审核，1:通过审核，2:未通过审核') ENUM('0','1','2')"`
	RecordStatus     string    `xorm:"not null default '0' comment('备案状态 0:未备案 1:已备案') ENUM('0','1')"`
	InstitutionCode  string    `xorm:"comment('运管统一编号') VARCHAR(16)"`
	Remark           string    `xorm:"VARCHAR(255)"`
	Isused           string    `xorm:"default '1' comment('1在使用 0已删除') ENUM('0','1')"`
}

func (e *Examiner) GetExaminerList(filter builder.Cond, pageSize int, offset int) (list []*response.ExaminerListResponse, count int64, err error) {
	err = engine.Table("dts_examiner").Alias("e").
		Select("e.id,e.school_id,e.status,e.approval_status,e.record_status,e.teaching_car_type,e.driving_car_type,e.entry_date,e.departure_date,e.licence_number,e.licence_grant_date,e.occupation_number,e.occupation_rank,u.name as Name,u.phone,u.nation,u.address,u.sex,u.nationality,u.district,u.id_number,u.id_type,u.native,dp.image_url,dp.institution_code as portrait_code").
		Join("LEFT", []string{"dts_user", "u"}, "e.user_id=u.id").
		Join("RIGHT", []string{"dts_portrait", "dp"}, "dp.id=e.portrait_id").
		Where(" e.isused=?", "1").And(filter).Desc("e.id").
		Limit(pageSize, offset).Find(&list)

	_, err = engine.Table("dts_examiner").Alias("e").Select("count(e.id) as count").Join("LEFT", []string{"dts_user", "u"}, "e.user_id=u.id").Where(" e.isused=?", "1").And(filter).Get(&count)
	if err != nil {
		return list, count, err
	}
	for k, _ := range list {
		list[k].Phone = strings.Replace(list[k].Phone, "e", "", -1)
		list[k].IdNumber = strings.Replace(list[k].IdNumber, "e", "", -1)
	}
	return list, count, nil
}

func (e *Examiner) GetInstitution(institutionCode string, user *User, photo string, finger string, province, city string) (examiner *Examiner, err error) {
	var (
		url       string
		retMap    map[string]interface{}
		leavedate string
		//req_type  int64
	)
	data := map[string]interface{}{
		"inscode": institutionCode,                             //培训机构编号
		"name":    user.Name,                                   //培训机构名称
		"sex":     user.Sex,                                    //性别
		"idcard":  strings.Replace(user.IdNumber, "e", "", -1), //身份证号
		"mobile":  strings.Replace(user.Phone, "e", "", -1),    //手机号码
		"address": user.Address,                                //联系地址
		"photo":   photo,                                       //照片文件ID
		//"fingerprint":     finger,                                      //指纹图片ID
		"drilicence":      e.LicenceNumber,                       //驾驶证号
		"fstdrilicdate":   e.LicenceGrantDate.Format("20060102"), //驾驶证初领日期
		"occupationno":    e.OccupationNumber,                    //职业资格证号
		"occupationlevel": e.OccupationRank,                      //职业资格等级
		"dripermitted":    e.DrivingCarType,                      //准驾车型
		"teachpermitted":  e.TeachingCarType,                     //准教车型
		"employstatus":    e.Status,                              //供职状态
		"hiredate":        e.EntryDate.Format("20060102"),        //入职日期
		//"leavedate":       leavedate,                                             //离职日期
	}
	if finger == "" {

	} else {
		data["fingerprint"] = finger
	}
	if e.Status == "0" {
		leavedate = ""
	} else {
		leavedate = e.DepartureDate.Format("20060102")
		data["leavedate"] = leavedate
	}
	//请求获取加密地址
	if url, err = GetSignURL("examiner", data, 1, province, city); err != nil {
		return e, err
	}
	param, err := json.Marshal(data)
	if err != nil {
		fmt.Println("json.Marshal failed:", err)
		return
	}
	var api_log ApiLog
	api_log.Url = url
	api_log.Param = string(param)
	api_log.Method = "POST"
	api_log.Time = time.Now()
	//请求运管
	if retMap, err = APIReq(url, data, "POST"); err != nil {
		result, _ := json.Marshal(retMap)
		api_log.Result = string(result)
		api_log.Add()
		return e, err
	}
	result, _ := json.Marshal(retMap)
	api_log.Result = string(result)
	api_log.Add()

	if retMap["errorcode"].(float64) != 0 {
		return e, errors.New(retMap["message"].(string))
	}
	if md, ok := retMap["data"].(map[string]interface{}); ok {
		e.InstitutionCode = fmt.Sprint(md["examnum"])
		return e, nil
	}
	return e, errors.New("获取考核员编号失败")
}

func (e *Examiner) RecordExaminer(institutionCode string, user *User, photo string, finger_code string, province string, city string, imageUrl string) (err error) {
	var (
		retMap  map[string]interface{}
		url     string
		reqType int64
		data    map[string]interface{}
	)
	if city == "130100" {
		reqType = 3
	} else {
		reqType = 2
	}
	data = map[string]interface{}{
		"inscode": institutionCode,                             //培训机构编号
		"examnum": e.InstitutionCode,                           //考核员编号
		"name":    user.Name,                                   //姓名
		"sex":     user.Sex,                                    //性别
		"idcard":  strings.Replace(user.IdNumber, "e", "", -1), //身份证号
		"mobile":  strings.Replace(user.Phone, "e", "", -1),    //手机号码
		"address": user.Address,                                //联系地址
		"photo":   photo,                                       //照片文件ID
		// "fingerprint":     finger_code,                                 //指纹图片ID
		"drilicence":      e.LicenceNumber,                       //驾驶证号
		"fstdrilicdate":   e.LicenceGrantDate.Format("20060102"), //驾驶证初领日期
		"occupationno":    e.OccupationNumber,                    //职业资格证号
		"occupationlevel": e.OccupationRank,                      //职业资格等级
		"dripermitted":    e.DrivingCarType,                      //准驾车型
		"teachpermitted":  e.TeachingCarType,                     //准教车型
		"employstatus":    e.Status,                              //供职状态0:在职1:离职
		"hiredate":        e.EntryDate.Format("20060102"),        //入职日期
	}
	if e.Status != "0" {
		data["leavedate"] = e.DepartureDate.Format("20060102")
	}
	if data["photo"], err = FileId(imageUrl, "examinerimg", reqType, province, city); err != nil {
		return err
	}
	//请求获取加密地址
	if url, err = GetSignURL("examiner", data, reqType, province, city); err != nil {
		return err
	}
	param, err := json.Marshal(data)
	if err != nil {
		fmt.Println("json.Marshal failed:", err)
		return
	}
	var api_log ApiLog
	api_log.Url = url
	api_log.Param = string(param)
	api_log.Method = "POST"
	api_log.Time = time.Now()
	//请求运管
	if retMap, err = APIReq(url, data, "POST"); err != nil {
		result, _ := json.Marshal(retMap)
		api_log.Result = string(result)
		api_log.Add()
		return err
	}
	result, _ := json.Marshal(retMap)
	api_log.Result = string(result)
	api_log.Add()
	log.Println(retMap)
	errorcode, _ := cast.ToIntE(retMap["errorcode"])
	if errorcode != 0 && !strings.Contains(retMap["message"].(string), "已经备案") {
		return errors.New(retMap["message"].(string))
	}
	return nil
}

func (e *Examiner) Edit(who ...string) bool {
	var (
		err error
	)
	_, err = engine.ID(e.Id).Cols(who...).Update(e)
	if err != nil {
		return false
	}
	return true
}

func (e *Examiner) GetById(id interface{}) (list *Examiner, err error) {
	list = new(Examiner)
	if _, err = engine.Table("dts_examiner").Where("id = ? and isused=?", id, "1").Get(list); err != nil {
		return list, err
	}
	return list, nil
}
